<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>HTML5 Canvas</title>
</head>
<body>
<canvas id="draw" width="800" height="800"></canvas>
<script>
const canvas = document.getElementById('draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
ctx.lineWidth = 100;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
let hue = 0;
let direction = false;

function draw(e){
  if(!isDrawing) return;

  ctx.beginPath();
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;  // 颜色
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.stroke();
  hue++;
  if(hue >= 360) {
    // reset
    hue = 0;
  }
  if(ctx.lineWidth > 100 || ctx.lineWidth <= 1) {
    direction = !direction;
  }
  if(direction) {
    ctx.lineWidth++;
  }else{
    ctx.lineWidth--;
  }
  // 记住上次位置
  [lastX, lastY] = [e.offsetX, e.offsetY];
}

canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e) => {
  isDrawing = true;
  // 重新开始位置
  [lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', ()=> isDrawing = false);


</script>

<style>
  html, body {
    margin: 0;
  }
</style>

</body>
</html>
